<template>
  <div v-if="!selectedKnowledgeId" class="knowledge-container">
    <h2 class="text-2xl font-bold mb-6">知识汇总</h2>
    
    <!-- 知识输入表单 -->
    <div class="input-form mb-8">
      <el-form :model="knowledgeForm" label-width="80px">
        <el-form-item label="标题">
          <el-input v-model="knowledgeForm.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="内容">
          <el-input 
            v-model="knowledgeForm.content" 
            type="textarea" 
            :rows="4"
            placeholder="请输入内容"
          ></el-input>
        </el-form-item>
        <el-form-item label="图片">
          <el-upload
            class="avatar-uploader"
            action="/api/knowledge/upload"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload"
          >
            <img v-if="knowledgeForm.imageUrl" :src="knowledgeForm.imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div v-if="knowledgeForm.imageUrl" class="mt-2">
            <el-button type="danger" size="small" @click="removeImage">移除图片</el-button>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addKnowledge">添加</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 知识卡片展示 -->
    <div class="knowledge-cards">
      <el-row :gutter="20">
        <el-col :span="8" v-for="item in knowledgeList" :key="item.id" class="mb-4">
          <el-card shadow="hover" class="knowledge-card" @click="viewKnowledgeDetail(item.id)">
            <template #header>
              <div class="card-header">
                <h3 class="card-title">{{ item.title }}</h3>
                <div class="card-actions">
                  <el-button 
                    type="danger" 
                    circle 
                    plain 
                    size="small"
                    @click.stop="removeKnowledge(item.id)"
                  >
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </div>
              </div>
            </template>
            <div class="card-content">
              <p class="card-text">{{ truncateText(item.content, 100) }}</p>
              
              <div v-if="item.imageUrl" class="card-image">
                <el-image 
                  :src="item.imageUrl"
                  fit="cover"
                  class="thumbnail"
                  lazy
                />
              </div>
              
              <div class="card-footer">
                <span class="text-xs text-gray-500">{{ formatDateTime(item.createTime) }}</span>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
  <knowledge-detail
    v-else
    :id="selectedKnowledgeId"
    @back="selectedKnowledgeId = null"
  />
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { Delete, Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import KnowledgeDetail from './KnowledgeDetail.vue'

export default {
  name: 'KnowledgeList',
  components: {
    Delete,
    Plus,
    KnowledgeDetail
  },
  setup() {
    const knowledgeForm = reactive({
      title: '',
      content: '',
      imageUrl: ''
    })
    
    const knowledgeList = ref([])
    const selectedKnowledgeId = ref(null)
    
    // 格式化时间
    const formatDateTime = (dateTimeStr) => {
      if (!dateTimeStr) return '未知时间'
      const date = new Date(dateTimeStr)
      return new Intl.DateTimeFormat('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        hour12: false
      }).format(date)
    }
    
    // 截断文本
    const truncateText = (text, length) => {
      if (!text) return ''
      return text.length > length ? text.substr(0, length) + '...' : text
    }
    
    // 从服务器获取知识列表
    const fetchKnowledgeList = async () => {
      try {
        const response = await axios.get('/api/knowledge')
        knowledgeList.value = response.data
      } catch (error) {
        console.error('获取知识列表失败:', error)
        ElMessage.error('获取知识列表失败')
      }
    }
    
    // 添加知识项
    const addKnowledge = async () => {
      if (!knowledgeForm.title.trim()) {
        ElMessage.warning('请输入标题')
        return
      }
      
      try {
        const response = await axios.post('/api/knowledge', knowledgeForm)
        knowledgeList.value.unshift(response.data)
        
        // 清空表单
        knowledgeForm.title = ''
        knowledgeForm.content = ''
        knowledgeForm.imageUrl = ''
        
        ElMessage.success('添加成功')
      } catch (error) {
        console.error('添加知识失败:', error)
        ElMessage.error('添加知识失败')
      }
    }
    
    // 删除知识项
    const removeKnowledge = async (id) => {
      try {
        await axios.delete(`/api/knowledge/${id}`)
        knowledgeList.value = knowledgeList.value.filter(item => item.id !== id)
        ElMessage.success('删除成功')
      } catch (error) {
        console.error('删除知识失败:', error)
        ElMessage.error('删除知识失败')
      }
    }
    
    // 查看知识详情
    const viewKnowledgeDetail = (id) => {
      selectedKnowledgeId.value = id
    }
    
    // 上传图片前检查
    const beforeUpload = (file) => {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isJpgOrPng) {
        ElMessage.error('只能上传JPG或PNG图片!')
        return false
      }
      
      const isLt2M = file.size / 1024 / 1024 < 5
      if (!isLt2M) {
        ElMessage.error('图片大小不能超过5MB!')
        return false
      }
      
      return true
    }
    
    // 上传成功处理
    const handleUploadSuccess = (res) => {
      knowledgeForm.imageUrl = res
      ElMessage.success('图片上传成功')
    }
    
    // 移除图片
    const removeImage = () => {
      knowledgeForm.imageUrl = ''
    }
    
    // 初始化时加载数据
    onMounted(() => {
      fetchKnowledgeList()
    })
    
    return {
      knowledgeForm,
      knowledgeList,
      selectedKnowledgeId,
      addKnowledge,
      removeKnowledge,
      viewKnowledgeDetail,
      formatDateTime,
      truncateText,
      beforeUpload,
      handleUploadSuccess,
      removeImage
    }
  }
}
</script>

<style scoped>
.knowledge-container {
  max-width: 1200px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  margin: 0;
  font-size: 1.2rem;
  font-weight: bold;
}

.card-content {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.card-text {
  flex-grow: 1;
  margin-bottom: 10px;
  white-space: pre-line;
}

.card-image {
  margin: 10px 0;
  height: 120px;
  overflow: hidden;
}

.card-footer {
  margin-top: auto;
  padding-top: 10px;
  border-top: 1px solid #eee;
}

.knowledge-card {
  height: 100%;
  cursor: pointer;
  transition: transform 0.3s;
}

.knowledge-card:hover {
  transform: translateY(-5px);
}

.thumbnail {
  width: 100%;
  height: 120px;
  object-fit: cover;
}

.avatar-uploader {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>